package com.xiongtian.springframework.core.io;

import cn.hutool.core.lang.Assert;
import com.xiongtian.springframework.util.ClassUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: xiongtian
 * @CreateTime: 2025-03-27  10:01
 * @Version: 1.0
 * @Description: 类路径资源加载类
 */

public class ClassPathResource implements Resource {

    private final String path;

    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, ((ClassLoader) null));
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "path must not be null");
        this.path = path;
        this.classLoader = classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader();
    }


    /**
     * 获取资源的输入流
     *
     * @return InputStream
     * @throws IOException IOException
     */
    @Override
    public InputStream getInputStream() throws IOException {
        InputStream is = classLoader.getResourceAsStream(path);
        if (null == is) {
            throw new FileNotFoundException(this.path + " cannot be opened because it does not exist");
        }
        return is;
    }
}
